<template>
  <div class="tree-node">
    <div class="node-content" :style="{ 'padding-left': `${level * 20 + 10}px` }" :class="{
      'has-children': hasChildren,
      'is-expanded': node.isExpanded,
      'is-leaf': !hasChildren
    }" @click="toggleExpand">
      <span class="expand-icon" v-if="hasChildren">
        {{ node.isExpanded ? '⊟' : '⊞' }}
      </span>
      <span class="leaf-icon" v-else>•</span>
      <span class="node-label">{{ node.name }}</span>
    </div>

    <div v-if="hasChildren && node.isExpanded" class="children-container">
      <TreeNode v-for="child in node.children" :key="child.id" :node="child" :level="level + 1"
        @node-click="$emit('node-click', $event)" />
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue';

const props = defineProps({
  node: {
    type: Object,
    required: true
  },
  level: {
    type: Number,
    default: 0
  }
});

const emit = defineEmits(['node-click']);

const hasChildren = computed(() => {
  return props.node.children && props.node.children.length > 0;
});

const toggleExpand = () => {
  if (hasChildren.value) {
    props.node.isExpanded = !props.node.isExpanded;
  }
  emit('node-click', props.node);
};
</script>

<style scoped>
.tree-node {
  margin: 2px 0;
}

.node-content {
  padding: 8px 10px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: all 0.2s;
}

.node-content:hover {
  background-color: #616161;
}

.node-content.has-children {
  font-weight: 500;
}

.node-content.is-expanded {
  color: #989a9b;
}

.node-content.is-leaf {
  color: #f0f0f0;
}

.expand-icon,
.leaf-icon {
  display: inline-block;
  width: 20px;
  text-align: center;
  font-size: 14px;
}

.expand-icon {
  color: #757575;
}

.leaf-icon {
  color: #9e9e9e;
}

.node-label {
  margin-left: 5px;
}

.children-container {
  border-left: 1px solid #e0e0e0;
  margin-left: 15px;
}
</style>